package tron.config;


import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

/**
 * @description web相关配置
 * @auther tron
 * @create 2020-01-21
 */
@Configuration
public class TronWebConfig implements WebMvcConfigurer {


    /**
     * 请求路径时间转换
     * @param registry
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new LocalDateTimeConverter());
        registry.addConverter(new DateConverter());
    }


    /**
     * 配置全局时间转换格式，即时实体类上不加注解也能正常转换时间类型
     * 自动按照格式化解析date类型日期
     */
    @Bean
    Jackson2ObjectMapperBuilderCustomizer javaTimeFormat() {
        return t -> {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            t.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
            t.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            t.dateFormat(simpleDateFormat);
        };
    }




    /**
     * 跨域请求放行
     *
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        //1.添加CORS配置信息
        CorsConfiguration corsConfig = new CorsConfiguration();
        //允许所有请求头
        corsConfig.setAllowedHeaders(Arrays.asList("*"));
        //允许所有方法
        corsConfig.setAllowedMethods(Arrays.asList("*"));
        //允许所有来源
        corsConfig.setAllowedOrigins(Arrays.asList("*"));
        //允许证书
        corsConfig.setAllowCredentials(true);
        //最大保存时间
        corsConfig.setMaxAge(36000L);
        //2.添加映射路径
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", corsConfig);
        //3.返回新的CorsFilter.
        return new CorsFilter(configSource);
    }


}
